package org.example.friend_test.controller;

import org.example.friend_test.entity.Friend;
import org.example.friend_test.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 朋友控制器
 */
@Controller
@RequestMapping("/friend")
public class FriendController {
    
    @Autowired
    private FriendService friendService;
    
    /**
     * 显示朋友列表页面（主页面）
     */
    @GetMapping("/list")
    public String showFriendList(Model model, HttpSession session) {
        // 检查用户是否已登录
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        
        // 获取当前登录用户
        Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
        Long userId = (Long) user.get("id");
        
        List<Friend> friends = friendService.findAllFriendsByUserId(userId);
        model.addAttribute("friends", friends);
        // 返回静态页面路径
        return "redirect:/friend-list.html";
    }
    
    /**
     * 获取朋友列表数据（API接口）
     */
    @GetMapping("/api/list")
    @ResponseBody
    public Map<String, Object> getFriendList(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            List<Friend> friends = friendService.findAllFriendsByUserId(userId);
            result.put("success", true);
            result.put("data", friends);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取朋友列表失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取朋友详情数据（API接口）
     */
    @GetMapping("/api/detail/{id}")
    @ResponseBody
    public Map<String, Object> getFriendDetail(@PathVariable Long id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            Friend friend = friendService.findFriendById(id, userId);
            if (friend != null) {
                result.put("success", true);
                result.put("data", friend);
            } else {
                result.put("success", false);
                result.put("message", "朋友不存在或无权限访问");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取朋友详情失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 显示添加朋友页面
     */
    @GetMapping("/add")
    public String showAddFriendPage(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        return "redirect:/add-friend.html";
    }
    
    /**
     * 添加新朋友
     */
    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addFriend(@RequestBody Friend friend, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            Friend newFriend = friendService.createFriend(friend, userId);
            result.put("success", true);
            result.put("message", "朋友添加成功");
            result.put("friend", newFriend);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加朋友失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 显示编辑朋友页面
     */
    @GetMapping("/edit/{id}")
    public String showEditFriendPage(@PathVariable Long id, Model model, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        
        // 获取当前登录用户
        Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
        Long userId = (Long) user.get("id");
        
        Friend friend = friendService.findFriendById(id, userId);
        if (friend != null) {
            model.addAttribute("friend", friend);
            return "redirect:/edit-friend.html?id=" + id;
        } else {
            return "redirect:/friend/list";
        }
    }
    
    /**
     * 更新朋友信息
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, Object> updateFriend(@RequestBody Friend friend, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            Friend updatedFriend = friendService.updateFriend(friend, userId);
            if (updatedFriend != null) {
                result.put("success", true);
                result.put("message", "朋友信息更新成功");
                result.put("friend", updatedFriend);
            } else {
                result.put("success", false);
                result.put("message", "更新失败：朋友不存在或无权限");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "朋友信息更新失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 删除朋友
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteFriend(@PathVariable Long id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            boolean success = friendService.deleteFriend(id, userId);
            if (success) {
                result.put("success", true);
                result.put("message", "朋友删除成功");
            } else {
                result.put("success", false);
                result.put("message", "删除失败：朋友不存在或无权限");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除朋友失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据姓名搜索朋友
     */
    @GetMapping("/search")
    public String searchFriends(@RequestParam String name, Model model, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        
        // 获取当前登录用户
        Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
        Long userId = (Long) user.get("id");
        
        List<Friend> friends = friendService.findFriendsByName(name, userId);
        model.addAttribute("friends", friends);
        model.addAttribute("searchName", name);
        // 返回静态页面路径
        return "redirect:/friend-search.html?name=" + name;
    }
    
    /**
     * 根据关系筛选朋友
     */
    @GetMapping("/filter")
    public String filterFriends(@RequestParam String relationship, Model model, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return "redirect:/user/login";
        }
        
        // 获取当前登录用户
        Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
        Long userId = (Long) user.get("id");
        
        List<Friend> friends = friendService.findFriendsByRelationship(relationship, userId);
        model.addAttribute("friends", friends);
        model.addAttribute("filterRelationship", relationship);
        // 返回静态页面路径
        return "redirect:/friend-filter.html?relationship=" + relationship;
    }
    
    /**
     * 搜索朋友API接口
     */
    @GetMapping("/api/search")
    @ResponseBody
    public Map<String, Object> searchFriendsApi(@RequestParam String name, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            List<Friend> friends = friendService.findFriendsByName(name, userId);
            result.put("success", true);
            result.put("data", friends);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "搜索朋友失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 筛选朋友API接口
     */
    @GetMapping("/api/filter")
    @ResponseBody
    public Map<String, Object> filterFriendsApi(@RequestParam String relationship, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }
        
        try {
            // 获取当前登录用户
            Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
            Long userId = (Long) user.get("id");
            
            List<Friend> friends = friendService.findFriendsByRelationship(relationship, userId);
            result.put("success", true);
            result.put("data", friends);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "筛选朋友失败：" + e.getMessage());
        }
        
        return result;
    }
}
